All files / web/src/app/api/worksheets/attempts/[attemptId] route.ts

0% Statements 0/79
0% Branches 0/1
0% Functions 0/1
0% Lines 0/79

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80                                                                                                                                                               
import { eq } from 'drizzle-orm'
import { type NextRequest, NextResponse } from 'next/server'
import { db } from '@/db'
import { problemAttempts, worksheetAttempts } from '@/db/schema'
import { withAuth } from '@/lib/auth/withAuth'

/**
 * Get grading results for a worksheet attempt
 *
 * Returns the grading status and full results once AI grading is complete.
 */
export const GET = withAuth(async (_request, { params }) => {
  try {
    const { attemptId } = (await params) as { attemptId: string }

    // Get attempt record
    const [attempt] = await db
      .select()
      .from(worksheetAttempts)
      .where(eq(worksheetAttempts.id, attemptId))

    if (!attempt) {
      return NextResponse.json({ error: 'Worksheet attempt not found' }, { status: 404 })
    }

    // Get individual problem results
    const problems = await db
      .select()
      .from(problemAttempts)
      .where(eq(problemAttempts.attemptId, attemptId))
      .orderBy(problemAttempts.problemIndex)

    // Parse JSON fields
    const errorPatterns = attempt.errorPatterns ? JSON.parse(attempt.errorPatterns) : []

    // Build response
    return NextResponse.json({
      attemptId: attempt.id,
      status: attempt.gradingStatus,
      uploadedAt: attempt.createdAt,
      gradedAt: attempt.gradedAt,
      errorMessage: attempt.errorMessage,

      // Results summary
      totalProblems: attempt.totalProblems,
      correctCount: attempt.correctCount,
      accuracy: attempt.accuracy,

      // Per-problem breakdown
      problems: problems.map((p) => ({
        index: p.problemIndex,
        problem: `${p.operandA} ${p.operator === 'addition' ? '+' : '-'} ${p.operandB}`,
        correctAnswer: p.correctAnswer,
        studentAnswer: p.studentAnswer,
        isCorrect: p.isCorrect,
        errorType: p.errorType,
        digitCount: p.digitCount,
        requiresRegrouping: p.requiresRegrouping,
      })),

      // AI analysis
      errorPatterns,
      aiSummary: attempt.aiFeedback,
      suggestedStepId: attempt.suggestedStepId,

      // Raw AI response for debugging
      aiResponseRaw: attempt.aiResponseRaw ? JSON.parse(attempt.aiResponseRaw) : null,
    })
  } catch (error) {
    console.error('Get attempt error:', error)
    return NextResponse.json(
      {
        error: 'Failed to fetch attempt',
        details: error instanceof Error ? error.message : 'Unknown error',
      },
      { status: 500 }
    )
  }
})